﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using PerfectBuyData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace PerfectBuyMVC.Controllers
{
    public class GuestBookController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Message = "Escriba un mensaje a nuestro libro de visitas.";

            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase fileBase, Entry entrie)
        {
            string filename = "/Images/thumb.png";

            if (fileBase != null && fileBase.ContentLength > 0)
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("AzureStorage"));

                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobClient.GetContainerReference("hugefiles");

                container.CreateIfNotExist();

                container.SetPermissions(new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Container
                    });

                CloudBlob blob = container.GetBlobReference(fileBase.FileName);

                filename = container.Uri + "/" + fileBase.FileName;

                blob.UploadFromStream(fileBase.InputStream);
            }

            perfectbuyEntities context = new perfectbuyEntities();
            Entry entrada = new Entry();
            entrada.mensaje = entrie.mensaje;
            entrada.nombre = entrie.nombre;
            entrada.urlImagen = filename;
            entrada.fecha = DateTime.Now;

            context.Entries.Add(entrada);
            context.SaveChanges();

            ViewBag.Entries = context.Entries.ToList();

            return RedirectToAction("Index");

            //return View(entrie);
            //return View();
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            perfectbuyEntities context = new perfectbuyEntities();
            ViewBag.Entries = context.Entries.ToList();
        }
    }
}